package cn.itcast.n8;

import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: AirMan
 * @date: 2025/4/25 13:13
 * @description:
 */
@Slf4j(topic = "c.TestPoolSemoPhore_my")
public class TestPoolSemoPhore_my {


    static class Pool {
        private int poolSize;
        private Connection[] connections;
        private AtomicIntegerArray states;
        private Semaphore semaphore;
        private ReentrantLock lock = new ReentrantLock();

        public Pool(int poolSize) {
            this.poolSize = poolSize;
            this.connections = new Connection[poolSize];
            this.states = new AtomicIntegerArray(poolSize);
            this.semaphore = new Semaphore(poolSize);
        }

        private Connection browse() {
            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            for (int i = 0; i < poolSize; i++) {
                if (states.get(i) == 0) {
                    if (states.compareAndSet(i, 0, 1)) {
                        log.debug("借到连接池...{}", i);
                        return connections[i];
                    }
                }
            }
            // 不会走到这里
            return null;
        }


        private void free(Connection connection) {
            for (int i = 0; i < poolSize; i++) {
                if (connection == connections[i]) {
                    states.set(i, 0);
                    log.debug("free {}", connection);
                    semaphore.release();
                }
                break;
            }
        }
    }
}
